# -*- coding: utf-8 -*-

"""
Module implementing FileParserUi.
"""

from PyQt4.QtGui import QMainWindow, QFileDialog, QMessageBox, QApplication
from PyQt4.QtCore import pyqtSignature, QString, QObject, SIGNAL, SLOT

from datetime import datetime
import os, re

from Ui_FileParser import Ui_MainWindow
from FileParser import parserEnregistrerTimestamperDonneesPlateforme, parserDonneesAccelero

class FileParserUi(QMainWindow, Ui_MainWindow):
    """
    Class documentation goes here.
    """
    def __init__(self, parent = None):
        """
        Constructor
        """
        QMainWindow.__init__(self, parent)
        self.setupUi(self)
        self.dateTimeEditDebutReel.setDateTime(datetime.now())
        self.dateTimeEditDebutVoulu.setDateTime(datetime.now())
        QObject.connect(self.dateTimeEditDebutReel, SIGNAL('dateTimeChanged(QDateTime)'), self.dateTimeEditDebutVoulu, SLOT('setDateTime(QDateTime)'))
        QObject.connect(self.comboBox, SIGNAL('currentIndexChanged(QString)'), self.modifierLabel)
        
    def modifierLabel(self):
        try:
            fichier = open(str(self.comboBox.currentText()))
            ligne = fichier.readline()
            fichier.close()
            pattern = re.compile(".*(?P<annee>\d{4})-(?P<mois>\d{2})-(?P<jour>\d{2})T(?P<heures>\d{2}):(?P<minutes>\d{2}):(?P<secondes>\d{2})")
            resultat = re.search(pattern, ligne)
            debutEnregistre = datetime(int(resultat.group('annee')), int(resultat.group('mois')), int(resultat.group('jour')), int(resultat.group('heures')), int(resultat.group('minutes')), int(resultat.group('secondes')))
    
            self.labelDateDebutRelleAccelerometres.setText(debutEnregistre.strftime("%d/%m/%Y %H:%M:%S"))
            self.dateTimeEditDebutReel_2 = debutEnregistre
            self.dateTimeEditDebutVoulu_2.setDateTime(debutEnregistre)
        except:
            pass

    @pyqtSignature("")
    def on_toolButtonPlateforme_clicked(self):
        """
        Bouton permettant de sélectionner le dossier où se situe le fichier de plateforme à modifier
        """
        self.nomFichierPlateforme = QFileDialog.getOpenFileName(None, self.trUtf8("Fichier à ouvrir"), QString(), self.trUtf8("*.txt"), None)
        self.lineEditFichierAModifierPlateforme.setText(self.nomFichierPlateforme)

    @pyqtSignature("")
    def on_pushButtonLancement_clicked(self):
        """
        """
        if self.dateTimeEditDebutReel.dateTime() > self.dateTimeEditDebutVoulu.dateTime():
            QMessageBox.warning(None, self.trUtf8("Attention !"), self.trUtf8("""La date voulue est antérieure à la date de l'enregistrement !"""), QMessageBox.StandardButtons(QMessageBox.Ok))
        else:
            drd = self.dateTimeEditDebutReel.dateTime().date()
            drt = self.dateTimeEditDebutReel.dateTime().time()
            dvd = self.dateTimeEditDebutVoulu.dateTime().date()
            dvt = self.dateTimeEditDebutVoulu.dateTime().time()
            debutReel = datetime(drd.year(), drd.month(), drd.day(), drt.hour(), drt.minute(), drt.second())
            debutVoulu = datetime(dvd.year(), dvd.month(), dvd.day(), dvt.hour(), dvt.minute(), dvt.second())
            parserEnregistrerTimestamperDonneesPlateforme(str(self.lineEditFichierAModifierPlateforme.text()), self.spinBoxFrequence.value(), debutReel, debutVoulu)
    

    @pyqtSignature("")
    def on_toolButtonAccelerometres_clicked(self):
        """
        """
        self.comboBox.clear()
        self.nomFichiersAccelerometres = QFileDialog.getOpenFileNames(None, self.trUtf8("Fichier(s) à ouvrir"), QString(), self.trUtf8("*.txt"), None)
        self.comboBox.addItems(self.nomFichiersAccelerometres)
        
    @pyqtSignature("")
    def on_pushButtonLancement_2_clicked(self):
        """
        """
        dvd = self.dateTimeEditDebutVoulu_2.dateTime().date()
        dvt = self.dateTimeEditDebutVoulu_2.dateTime().time()
        debutVoulu = datetime(dvd.year(), dvd.month(), dvd.day(), dvt.hour(), dvt.minute(), dvt.second())
        for chemin in self.nomFichiersAccelerometres:
            res = re.search('\d{4}-\d{2}-\d{2}_\d{2}-\d{2}-\d{2}_(.*)_(.*)_(accelero.*)', str(chemin))
            lignes = parserDonneesAccelero(str(chemin), debutVoulu)
            fichier = open(os.path.join(os.path.dirname(str(chemin)), debutVoulu.strftime("%Y-%m-%d_%H-%M-%S_") + "%s_%s_%s" % (res.group(1), res.group(2), res.group(3))), 'w')
            fichier.write(lignes)
